package wml.clipstore.storage.clips;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Date;
import java.util.List;

import CLIPSJNI.Environment;
import CLIPSJNI.FactAddressValue;

import test.beans.User;
import wml.clipstore.base.Criteria;
import wml.clipstore.base.Entity;
import wml.clipstore.map.MapManager;

public class ClipsStorage {

	private MapManager manager = MapManager.getInstance();
	private Environment clips = new Environment();

	private ClipsSaver saver = new ClipsSaver(manager, clips);
	private ClipsGetter getter = new ClipsGetter(manager, clips);

	public static void main(String args[]) {
		ClipsStorage clips = new ClipsStorage();
		User user = new User();
		user.setAge(21);
		user.setGender("男");
		user.setName("WangMingliang");
		clips.save(user);
		clips.persist();
		//Date s = new Date();
		//User u = clips.get(User.class, "name", "WangMingliang", String.class);
		//Date e = new Date();
		//System.out.println(":"+(e.getTime()-s.getTime()));
		//System.out.println(u.getGender());
		clips.close();
	}

	public void close() {
		this.clips.clear();
		this.clips.destroy();
	}

	public ClipsStorage() {
		init();
	}

	private void init() {
		try {
			File file = this.writeToFile(this.manager.getTemplates());
			clips.load(file.getAbsolutePath());
			file.delete();
			clips.loadFacts("C://clips/facts.clp");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private File writeToFile(List<String> templates) throws IOException {
		File file = File.createTempFile("init", ".clp");
		FileWriter w = new FileWriter(file);
		for (String t : templates){
			w.write(t);
			w.flush();
		}
		w.close();
		return file;
	}

	public void persist() {
		clips.eval("(save C://clips/init.clp)");
		clips.eval("(save-facts C://clips/facts.clp)");
	}

	public void save(Entity entity) {
		this.saver.save(entity);
	}

	public <T extends Entity> T get(Class<T> clazz, String field, String value,
			Class<?> valueType) {
		FactAddressValue fav = this.getter.getFact(clazz.getName(), field, "\""
				+ value + "@" + valueType.getName() + "\"");
		if (fav == null)
			return null;
		
		Date s = new Date();
		T entity = this.getter.getEntity(fav);
		Date e = new Date();
		System.out.println("ee:"+(e.getTime()-s.getTime()));
		
		return entity;
	}

	public void get(Class<? extends Entity> clazz, Criteria... criteria) {

	}
}